package com.app.micaihu.view.newsdetail;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.app.micaihu.R;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.custom.view.HackyViewPager;
import com.app.micaihu.custom.view.PhotoImageView;
import com.app.micaihu.utils.OkHttp3Helper;
import com.app.micaihu.view.newsdetail.adapter.NewsImageDetailAdapter;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.osutils.StatusBarUtils;

import java.io.File;
import java.util.ArrayList;

//import com.app.micaihu.custom.components.net.OKHttpUtils;

/**
 * Created by Guo on 2016/8/3.
 * <p>
 * 新闻详情点击进来的图片viewpager
 */
public class ImageShowActivity extends BaseOldActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, PhotoImageView.ImagePhotoViewListener {

    private HackyViewPager hackyViewPager;
    private TextView tvDesc;
    private TextView tvAppTitle;
    private ImageView ivAppRight;
    private Intent intent;
    private ArrayList<String> imageList;
    private int num;
    private boolean misScrolled;

    private NewsImageDetailAdapter mNewsImageDetailAdapter;
    private String title;


    private static final int SUCCESS = 1010;
    private static final int FAIL = 1011;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    try {
                        String filePath = (String) msg.obj;
                        ToastUtils.makeText(getResources().getString(R.string.detail_image_down_prompt));
                    } catch (Exception e) {

                    }

                    break;
                case FAIL:
                    ToastUtils.makeText("下载失败,网络异常");
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isInit = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newsimagedetail);
        StatusBarUtils.setupStatusBarView(this, R.color.common_bg_color_8, R.color.common_bg_color_8);

        intent = getIntent();
        if (intent != null) {
            imageList = intent.getStringArrayListExtra(Config.Extra.PARAMETER1);
            num = intent.getIntExtra(Config.Extra.PARAMETER2, 0);
            title = intent.getStringExtra("title") != null ? intent.getStringExtra("title") : "";

            if (imageList == null || imageList.size() <= 0) {
                ToastUtils.makeText(getResources().getString(R.string.neterror));
                finish();
            }
        } else {
            ToastUtils.makeText(getResources().getString(R.string.neterror));
            finish();
        }

        initView();

        showData();


    }

    private void showData() {

        if (hackyViewPager != null) {
            if (mNewsImageDetailAdapter == null) {
                mNewsImageDetailAdapter = new NewsImageDetailAdapter(imageList);
                mNewsImageDetailAdapter.setImageClickListener(this);
                hackyViewPager.setAdapter(mNewsImageDetailAdapter);
                hackyViewPager.setPageMargin(ViewSizeUtils.dp2px(this, 30));
            } else {
                mNewsImageDetailAdapter.notifyDataSetChanged();
            }

//            mNewsImageDetailAdapter.setOnPhotoClickListener(this);
            hackyViewPager.setCurrentItem(num);
        }

        if (tvDesc != null) {
            setContentTxt(num);
        }

    }

    private void initView() {
        hackyViewPager = (HackyViewPager) findViewById(R.id.hvp_imagecontainer);
        tvDesc = (TextView) findViewById(R.id.tv_desc);

        tvAppTitle = (TextView) findViewById(R.id.tv_apptitle);
        ivAppRight = (ImageView) findViewById(R.id.tv_appright);
        tvAppTitle.setVisibility(View.GONE);
        ivAppRight.setImageResource(R.drawable.imagedetail_download_selector);

        ivAppRight.setOnClickListener(this);
        hackyViewPager.addOnPageChangeListener(this);

    }

    /**
     * 设置图库的描述
     *
     * @param position
     */
    private void setContentTxt(int position) {

        String strContent = title + "\n" + (position + 1) + "/" + imageList.size();
        String strTitle = title + "\n";
        String currentPageNum = title + "\n" + (position + 1) + "/";


        SpannableString styledText = new SpannableString(strContent);

        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_font_size_16), 0, strTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_font_size_18), strTitle.length(), currentPageNum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_font_size_14), currentPageNum.length(), strContent.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (tvDesc != null) {
            tvDesc.setText(styledText, TextView.BufferType.SPANNABLE);
        }

    }


    @Override
    public void onClick(View v) {

        if (v == null) return;
        switch (v.getId()) {
            case R.id.tv_appright:
                String fileName = imageList.get(num).substring(imageList.get(num).lastIndexOf("/") + 1) + ".jpg";
                OkHttp3Helper.getInstance().downAsynFile(imageList.get(num), AppConfigTools.USERSAVEIMG, fileName, onDownLoadResponCallBack);

                break;
        }
    }


    private OkHttp3Helper.OnDownLoadResponCallBack onDownLoadResponCallBack = new OkHttp3Helper.OnDownLoadResponCallBack() {
        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void onFailure() {
            super.onFailure();
            handler.sendEmptyMessage(FAIL);
        }

        @Override
        public void onSucess(File file) {
            super.onSucess(file);
            if (file == null) {
                handler.sendEmptyMessage(FAIL);
                return;
            }
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            Message msg = Message.obtain();
            msg.what = SUCCESS;
            msg.obj = file.getAbsolutePath();
            handler.sendMessage(msg);
        }
    };


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        num = position;
        setContentTxt(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_DRAGGING:
                misScrolled = false;
                break;
            case ViewPager.SCROLL_STATE_SETTLING:
                misScrolled = true;
                break;
            case ViewPager.SCROLL_STATE_IDLE:
//                if (hackyViewPager.getCurrentItem() == hackyViewPager.getAdapter().getCount() - 1
//                        && !misScrolled) {
//                    ToastUtils.makeText(getResources().getString(R.string.common_nomore));
//                }
                misScrolled = true;
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0, R.anim.base_alpha_out);
    }


    @Override
    public void onOneStepClick() {
        onBackPressed();
    }

    @Override
    public void onLongStepClick() {

    }
}
